import { listClassInfoVoByPageUsingPost } from '@/services/backend/classInfoController';
import { joinUserClassRelationUsingPost } from '@/services/backend/userClassRelationController';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { useModel } from '@umijs/max';
import { message, Space, Typography } from 'antd';
import React, { useRef } from 'react';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;

  /**
   *  Join node
   * @zh-CN 加入节点
   *
   * @param row
   */
  const handleJoin = async (row: API.ClassInfo) => {
    const hide = message.loading('正在加入');
    if (!row) return true;
    try {
      await joinUserClassRelationUsingPost({
        classId: row.id,
        userId: currentUser?.id,
      });
      hide();
      message.success('加入成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('加入失败，' + error.message);
      return false;
    }
  };

  const columns: ProColumns<API.ClassInfoVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '班级名称',
      dataIndex: 'className',
      valueType: 'text',
    },
    {
      title: '班级描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '负责教练姓名',
      dataIndex: ['user', 'username'],
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '班级状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '开启', status: 'active' },
        archived: { text: '关闭', status: 'archived' },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            type="success"
            onClick={() => {
              handleJoin(record);
            }}
          >
            加入
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.ClassInfo>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listClassInfoVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.ClassInfoQueryRequest);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
    </PageContainer>
  );
};
export default TableList;
